package com.dc.schedule.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;


/**
 * <p>Descriptions...
 *
 * @author Diamon.Cheng
 * @date ${DATE}.
 */
@Slf4j
public class Main {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        final ChannelHandlerContext[] ctx0 = {null};
//        new Thread(() -> {
//            Scanner scanner = new Scanner(System.in);
//            while (true) {
//                String str = scanner.nextLine();
//                if ("exit".equals(str)) {
//                    break;
//                }
//                if (ctx0[0] == null) {
//                    continue;
//                }
//                ctx0[0].writeAndFlush(Unpooled.unreleasableBuffer(
//                        Unpooled.copiedBuffer("{\"message\":\"" + str + "\"}", StandardCharsets.UTF_8)));
//            }
//
//        }).start();
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new JsonObjectDecoder())
                            .addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                                    ctx0[0] = ctx;
                                }
                                
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    ByteBuf buf = (ByteBuf) msg;
                                    byte[] bytes = new byte[buf.readableBytes()];
                                    buf.readBytes(bytes);
                                    String json = new String(bytes, StandardCharsets.UTF_8);
                                    log.info("接收到消息, {}, {}", ctx, json);
                                    System.out.println("接收到消息" + json);
                                    buf.release();
                                }
                                
                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    log.error("连接发生异常", cause);
                                    System.out.println("连接发生异常" + cause);
                                }
                                
                                @Override
                                public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
                                    log.error("连接取消注册 {}", ctx.channel());
                                    System.out.println("连接取消注册" + ctx.channel());
                                    workerGroup.shutdownGracefully();
                                }
                            
                            
                            });
                }
            });
            
            // Start the client.
            ChannelFuture f = b.connect("localhost", 2334); // (5)
            
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
